package com.yfjin.webrtc.ws;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

public class WsServer extends WebSocketServer {
    private static final String TAG = "123123";
    private IPeerConnection mPeerConnection;

    public WsServer(IPeerConnection peerConnection,int mPort) {
        super(new InetSocketAddress(mPort));
        mPeerConnection = peerConnection;
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        mPeerConnection.newConnection(webSocket.getRemoteSocketAddress().getAddress().getHostName());
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        Log.i(TAG, "onClose: 关闭 socket ");
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {

    }

    @Override
    public void onMessage(WebSocket conn, ByteBuffer bytes) {
        byte[] buf = new byte[bytes.remaining()];
        bytes.get(buf);
        mPeerConnection.remoteReceiveData(conn.getRemoteSocketAddress().getAddress().getHostName(), buf);
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
    }

    @Override
    public void onStart() {

    }
}
